<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="formInline.status" placeholder="请选择">
          <el-option label="全部" value=""></el-option>
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formInline.userName" placeholder="输入用户名称"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-input size="small" v-model="formInline.phonenumber" placeholder="输入手机号"></el-input>
      </el-form-item>

      <el-form-item label="" >
        <el-col :span="11">
          <el-form-item>
            <el-date-picker size="small" type="date" placeholder="最后登录时间" v-model="formInline.date1"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1">-</el-col>
        <el-col :span="11">
          <el-form-item>
            <el-date-picker size="small" type="date" placeholder="最后登录时间" v-model="formInline.date2"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="">
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleBatchDel">批量删除</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" @selection-change="handleSelectionChange" :data="userData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">
      </el-table-column>
      <el-table-column align="center" prop="userId" label="用户ID" width="120">
      </el-table-column>
      <el-table-column align="center"  prop="userName" label="用户账号" width="120">
      </el-table-column>
      <el-table-column align="center"  prop="nickName" label="昵称" width="120">
      </el-table-column>
      <el-table-column align="center"  prop="password" label="密码" width="120">
      </el-table-column>
      <el-table-column align="center"  prop="sex" label="性别" min-width="50">
      </el-table-column>
      <el-table-column align="center"  prop="phonenumber" label="手机号" min-width="120">
      </el-table-column>
      <el-table-column align="center"  prop="email" label="邮件" min-width="120">
      </el-table-column>
      <el-table-column align="center"  prop="createTime" label="创建时间" min-width="150">
        <template slot-scope="scope">
          <div>{{scope.row.createTime|timestampToTime}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center"  prop="status" label="状态" min-width="60">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status==='0'?show:noshow" active-color="#13ce66" inactive-color="#ff4949" @change="editType(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <!--
      Pagination组件是自己封装的组件，在user.vue中导入、注册并使用该组件
      通过v-bind:child-msg="pageparm"将参数传递给Pagination(父传子，子中用props接收)
      -------------
      在子组件中使用自定义时间调用父组件中的callFather，将子中数据传递给父组件
    -->
    <Pagination v-bind:child-msg="pageparm" v-model="pageparm" @callFather="callFather"></Pagination>
    <!-- 添加/编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules">
        <el-form-item label="用户账号" prop="userName">
          <el-input size="small" v-model="editForm.userName" auto-complete="off" placeholder="请输入用户账号"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input size="small" v-model="editForm.nickName" auto-complete="off" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input size="small" v-model="editForm.password" auto-complete="off" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="editForm.sex" label="0">男</el-radio>
          <el-radio v-model="editForm.sex" label="1">女</el-radio>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input size="small" v-model="editForm.phonenumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input size="small" v-model="editForm.email" placeholder="请输入邮箱地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import {
  userList,
  userEdit,
  userSave,
  userDelete,
  userLock,
  userBatchDel,
} from '../../api/userMG'
import Pagination from '../../components/Pagination.vue'
import {timestampToTime} from "../../utils/util";
import row from "html-webpack-plugin/lib/chunksorter";
import * as user from "../../api/userMG";
export default {
  computed: {
    // show() {
    //   return show
    // }
  },
  data() {
    return {
      show: true, //switch开启
      noshow: false, //switch关闭
      loading: false, //是显示加载
      title: '添加用户',
      editFormVisible: false, //控制编辑页面显示与隐藏
      // 编辑与添加
      editForm: {
        userId: '',
        userName: '',
        nickName: '',
        password: '',
        sex: '',
        phonenumber: '',
        email: ''
      },
      // 部门参数
      unitparm: {
        userIds: '',
        deptId: '',
        deptName: ''
      },
      // 选择数据
      selectdata: [],
      //删除时用来接收数据的
      multipleSelection: [],
      // rules表单验证
      rules: {
        userName: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
        ]
      },
      // 请求数据参数
      formInline: {
        page: 1,
        limit: 10,
        userName: '',
        phonenumber: '',
        status: '',
        date1: '',
        date2: '',
      },
      //用户数据
      userData: [],
      // 数据权限
      UserDept: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: '',
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },

  watch: {},

  /**
   * 创建完毕
   */
  created() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    timestampToTime,
    // 获取数据方法
    getdata(parameter) {
      this.loading = true
      // 获取用户列表
      userList(parameter).then(res => {
        this.loading = false
        if (res.code !== 2000) {
          this.$message({
            type: 'info',
            message: res.msg
          })
        } else {
          const pageInfo = res.data;
          // console.log("res.data是什么",res.data)
          this.userData = pageInfo.list;

          // 分页赋值
          //TODO
          this.pageparm.currentPage = this.formInline.pageNum
          this.pageparm.pageSize = this.formInline.pageSize
          this.pageparm.total = pageInfo.total
        }
      })
    },
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage
      this.formInline.limit = parm.pageSize
      this.getdata(this.formInline)
    },
    //搜索事件
    search() {
      //前端解决方法
      //如果日期为null，就将''赋值给前面变量
      //如果日期不为null，就将日期正常赋值
      this.formInline.date1 = this.formInline.date1 || ''
      this.formInline.date2 = this.formInline.date2 || ''
      this.getdata(this.formInline)
    },

    // 修改type
    //根据id获得该行的状态，才能进行改变
    editType: function (row) {
      this.loading = true
      let parm = {
        status: '',
        userId: '',
      }
      parm.userId = row.userId
      let lock = row.status
      if (lock === '0') {
        parm.status = 'show'
      } else {
        parm.status = 'noshow'
      }
      // 修改状态
      userLock(parm).then(res => {
        this.loading = false
        if (res.code !== 2000) {
          this.$message({
            type: 'info',
            message: res.msg
          })
        } else {
          this.$message({
            type: 'success',
            message: '状态修改成功'
          })
          this.getdata(this.formInline)
        }
      })
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.editFormVisible = true
      // console.log("row----",row)
      /**
       * 判断执行编辑还是添加
       * row是该行的数据，如果row不是未定义，不是空的就表示要执行编辑
       * 否则就执行添加
       */
      if (row !== undefined && row !== 'undefined') {
        this.title = '编辑'
        this.editForm.userId = row.userId
        this.editForm.userName = row.userName
        this.editForm.nickName = row.nickName
        this.editForm.password = row.password
        this.editForm.sex = row.sex
        this.editForm.phonenumber = row.phonenumber
        this.editForm.email = row.email
      } else {
        this.title = '添加'
        this.editForm.userId = ''
        this.editForm.userName = ''
        this.editForm.nickName = ''
        this.editForm.password = ''
        this.editForm.sex = ''
        this.editForm.phonenumber = ''
        this.editForm.email = ''
      }
    },
    // 编辑和添加
    submitForm(editData) {
      //校验
      this.$refs[editData].validate(valid => {
        //校验通过发送请求
        if (valid) {
          // 当title为添加时，执行添加
          if (this.title === "添加") {
            // 实现添加
            userSave(this.editForm).then(res => {
              if (res.code === 2000) {
                this.editFormVisible = false;
                this.$message.success({
                  message: '用户添加成功',
                  duration: 500
                })
                this.getdata(this.formInline)
              } else {
                this.$message.error({
                  message: '用户添加失败',
                  duration: 500
                })
              }
            })
          }
          // 当title为编辑时，执行编辑
          else if (this.title === "编辑") {
            console.log(this.editForm)
            userEdit(this.editForm).then(res => {
              if (res.code === 2000) {
                this.editFormVisible = false;
                this.$message.success({
                  message: '用户编辑成功',
                  duration: 500
                })
                this.getdata(this.formInline)
              } else {
                this.$message.error({
                  message: '用户编辑失败',
                  duration: 500
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    //删除
    deleteUser(userId) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userDelete(userId).then(res => {
          if (res.code === 2000) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getdata(this.formInline)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 选择复选框事件
    handleSelectionChange(val) {
      var idArr = []
      for (let i = 0; i < val.length; i++) {
        idArr.push(val[i].userId)
      }
      this.multipleSelection = idArr;
    },
    //批量删除
    handleBatchDel() {
      this.$confirm('批量删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("接收到的id",this.multipleSelection)
        userBatchDel( this.multipleSelection).then(res => {
          if (res.code == 2000) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.formInline.pageNum = 1;
            this.getdata(this.formInline)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
        // 关闭编辑、增加弹出框
        closeDialog(dialog)
      {
        if (dialog === 'edit') {
          this.editFormVisible = false
        } else if (dialog === 'perm') {
          this.dataAccessshow = false
        } else if (dialog === 'unit') {
          this.unitAccessshow = false
        }
      }

  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>


